#include "stackc.h"


void runstackdemo(){
        STACK Stack;//创建agiel栈变量
        int val = 0;//
        initStack(&Stack);
        IsEmpty(&Stack);
        pushStack(&Stack, 100);
        pushStack(&Stack, 200);
        pushStack(&Stack, 300);
        pushStack(&Stack, 400);
        pushStack(&Stack, 500);
        pushStack(&Stack, 600);
        IsEmpty(&Stack);
        traverseStack(&Stack);
        popStack(&Stack, &val);
        traverseStack(&Stack);
        clearStack(&Stack);
        IsEmpty(&Stack);
}

void initStack(PSTACK Stack){
        PNODE Pnew = (PNODE)malloc(sizeof(NODE));
        if(Pnew == NULL) {
                printf("分配失败\n");
                exit(-1);
        }
        Stack->PTOP = Pnew;
        Stack->PBOTTOM=Pnew;
        Pnew->next=NULL;
        printf("栈创建成功!");
}
void pushStack(PSTACK Stack, int val){
        PNODE p = (PNODE)malloc(sizeof(NODE));
        if(p == NULL) {
                printf("分配失败\n");
                exit(-1);
        }
        p->element=val;
        p->next=Stack->PTOP;
        Stack->PTOP=p;
        printf("%d入栈成功", val);
}
void popStack(PSTACK Stack, int *val){
        if(Stack->PBOTTOM==Stack->PTOP) {
                printf("出栈失败!\n");
        }
        PNODE p = Stack->PTOP;
        *val = p->element;
        Stack->PTOP=p->next;
        free(p);
        p = NULL;
        printf("已将%d从栈弹出！", *val);
}
void traverseStack(PSTACK Stack){
        if(IsEmpty(Stack)) {
                printf("遍历栈为空，栈为空!");
                exit(-1);
        }
        PNODE p = Stack->PTOP;
        printf("遍历栈的结果为：");
        while(p != Stack->PBOTTOM){
                printf("%d ", p->element);
                p = p->next;
        }
        printf("\n");
}
bool IsEmpty(PSTACK Stack){
        if(Stack->PBOTTOM==Stack->PTOP) {
                printf("栈为空\n");
                return true;
        } else {
                return false;
        }
}
void clearStack(PSTACK Stack){
        if(IsEmpty(Stack)) {
                printf("栈为空，无需\n");
                exit(-1);
        }
        //创建两个节点指针用来释放栈
        PNODE p = Stack->PTOP;
        PNODE q = NULL;
        //清空栈
        while(p != Stack->PBOTTOM){
                q = p->next;
                free(p);
                p = q;
        }
        Stack->PTOP=Stack->PBOTTOM;//栈顶指向的初始空节点
        printf("已清空栈");
}
